import { ref, watch, onUnmounted, type Ref } from 'vue'

export function useLocalStorage<T>(
  key: string,
  defaultValue: T,
  options: {
    serializer?: {
      read: (value: string) => T
      write: (value: T) => string
    }
  } = {},
) {
  const {
    serializer = {
      read: JSON.parse,
      write: JSON.stringify,
    },
  } = options

  // 从 localStorage 读取初始值
  const read = (): T => {
    try {
      const item = localStorage.getItem(key)
      if (item === null) {
        return defaultValue
      }
      return serializer.read(item)
    } catch (error) {
      console.warn(`Error reading localStorage key "${key}":`, error)
      return defaultValue
    }
  }

  // 写入 localStorage
  const write = (value: T): void => {
    try {
      localStorage.setItem(key, serializer.write(value))
    } catch (error) {
      console.error(`Error setting localStorage key "${key}":`, error)
    }
  }

  // 删除 localStorage 项
  const remove = (): void => {
    try {
      localStorage.removeItem(key)
      storedValue.value = defaultValue
    } catch (error) {
      console.error(`Error removing localStorage key "${key}":`, error)
    }
  }

  const storedValue = ref<T>(read())

  // 监听值的变化并同步到 localStorage
  watch(
    storedValue,
    (newValue) => {
      if (newValue === undefined || newValue === null) {
        remove()
      } else {
        write(newValue)
      }
    },
    { deep: true },
  )

  // 手动设置值的方法
  const setValue = (value: T) => {
    storedValue.value = value
  }

  // 监听其他标签页的 localStorage 变化
  const handleStorageChange = (e: StorageEvent) => {
    if (e.key === key && e.newValue !== null) {
      try {
        storedValue.value = serializer.read(e.newValue)
      } catch (error) {
        console.warn(`Error syncing localStorage key "${key}":`, error)
      }
    }
  }

  window.addEventListener('storage', handleStorageChange)

  // 组件卸载时清理事件监听器
  onUnmounted(() => {
    window.removeEventListener('storage', handleStorageChange)
  })

  return [storedValue, setValue, remove] as const
}
